{% extends 'main_hub/user_base.html' %}

{% block title %}
    消息
{% endblock %}

{% block css %}
    <style>
        .chatDialogBox {
            background-color: lightgrey;
            color: #000;
            border: 1px solid lightgrey;
            min-height: 20px;
            padding: 8px 15px;
            word-break: break-all;
            position: relative;
            border-radius: 5px;
            display: inline-block;
            font-size: 14px;
        }

        .chatDialogBox:before, .chatDialogBox:after {
            content: "";
            display: block;
            position: absolute;
            width: 0;
            height: 0;
            border: 6px solid transparent;
            border-right-color: lightgrey;
            left: -11px;
            top: 10px;
            z-index: 1;
        }

        .chatDialogBox:after {
            left: -12px;
            border-right-color: lightgrey;
            z-index: 0;
        }


        .chatDialogBoxMe {
            background-color: lawngreen;
            color: #000;
            border: 1px solid lawngreen;
            min-height: 20px;
            padding: 8px 15px;
            word-break: break-all;
            position: relative;
            border-radius: 5px;
            display: inline-block;
            font-size: 14px;
        }

        .chatDialogBoxMe:before, .chatDialogBoxMe:after {
            content: "";
            display: block;
            position: absolute;
            width: 0;
            height: 0;
            border: 6px solid transparent;
            border-right-color: lawngreen;
            left: -11px;
            top: 10px;
            z-index: 1;
        }

        .chatDialogBoxMe:after {
            left: -12px;
            border-right-color: lawngreen;
            z-index: 0;
        }
    </style>
{% endblock %}

{% block content %}
    {% if not_recipient_user or all_user_dic %}
        <div class="container">
            <div class="row border" style="height: 720px;border-radius: 10px">
                <br>
                <div class="col-3 overflow-auto border-right" style="height: 710px;">
                    <div class="nav flex-column nav-pills " id="v-pills-tab" role="tablist" aria-orientation="vertical">
                        <br>
                        {% for g_user, values in all_user_dic.items %}
                            <a class="nav-link{% if values.0.username == recipient_user.username %} active{% endif %}"
                               id="v-pills-home-tab{{ forloop.counter }}"
                               data-toggle="pill" href="#v-pills-home{{ forloop.counter }}" role="tab"
                               aria-controls="v-pills-home"
                               aria-selected="true"
                               onclick="window.location.href='{% url 'user_message' %}?recipient_username={{ values.0.username }}'">
                                {% if values.0.nick_name %}
                                    {{ values.0.nick_name }}
                                    {% if values.1 == False %}
                                    <div style="width: 8px;height: 8px;border-radius: 4px;background-color: red;display:inline-block"></div>
                                {% endif %}
                                {% else %}
                                    用户：{{ values.0.username }}{% if values.1 == False %}
                                    <div style="width: 8px;height: 8px;border-radius: 4px;background-color: red;display:inline-block"></div>
                                {% endif %}
                                {% endif %}
                            </a>
                        {% endfor %}
                        {% if not_recipient_user %}
                            <a class="nav-link active"
                               id="v-pills-home-tab0"
                               data-toggle="pill" href="#v-pills-home0" role="tab"
                               aria-controls="v-pills-home"
                               aria-selected="true"
                               onclick="window.location.href='{% url 'user_message' %}?recipient_username={{ g_user.username }}'">
                                {% if not_recipient_user.nick_name %}
                                    {{ not_recipient_user.nick_name }}
                                {% else %}
                                    用户：{{ not_recipient_user.username }}
                                {% endif %}
                            </a>
                        {% endif %}
                    </div>
                </div>

                <div class="col-1"></div>
                <div class="col-7">
                    <br>
                    <div class="row border overflow-auto" style="height: 500px;border-radius: 40px" id="wrapper">
                        <div id="send_message1" class="tab-pane fade show active "
                             style="margin-left: 30px;margin-right: 30px">
                            <br>
                            {% for ms in all_message %}
                                <div class="row">
                                    <div class="col">
                                        <div class="media">
                                            <img src="{{ MEDIA_URL }}{{ ms.user.image }}" class="mr-3" alt="..."
                                                 style="width: 50px; height: 50px; border-radius: 25px">
                                            <div class="media-body">
                                                {% if ms.user == request.user %}
                                                    <div class="chatDialogBoxMe">{{ ms.message }}</div>
                                                    <p style="font-size: 10px;color: grey">{{ ms.add_time.time }} {{ ms.add_time.month }}.{{ ms.add_time.day }}</p>
                                                {% else %}
                                                    <div class="chatDialogBox">{{ ms.message }}</div>
                                                    <p style="font-size: 10px;color: grey">{{ ms.add_time.time }} {{ ms.add_time.month }}.{{ ms.add_time.day }}</p>
                                                {% endif %}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <br>
                            {% endfor %}
                        </div>
                    </div>
                    <br>
                    <div class="row" style="height: 100px">
                        <textarea id="txt" placeholder="请输入"
                                  style="width: 800px;resize: none;border-radius: 10px"></textarea>
                    </div>
                    <br>
                    <div class="row">
                        <button type="button" class="btn btn-primary" onclick="sendMessage()">发送</button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <div id="talk_error" class="text-danger"></div>
                    </div>
                </div>
                <div class="col-1"></div>
            </div>

        </div>
    {% else %}
        <div class="container">
            <div class="row justify-content-md-center align-items-center" style="height: 500px">
                <i class="bi bi-chat-left-dots">暂无讯息</i>
            </div>
        </div>
    {% endif %}
{% endblock %}


{% block custom_jss %}
    <script>
        {#    滑动滚动条#}
        setTimeout(scrollToBottom, 100);

        function scrollToBottom() {
            const domWrapper = document.querySelector('#wrapper'); // 外层容器 出现滚动条的dom
            (function smoothscroll() {
                const currentScroll = domWrapper.scrollTop;   // 已经被卷掉的高度
                const clientHeight = domWrapper.offsetHeight; // 容器高度
                const scrollHeight = domWrapper.scrollHeight; // 内容总高度
                if (scrollHeight - 10 > currentScroll + clientHeight) {
                    window.requestAnimationFrame(smoothscroll);
                    domWrapper.scrollTo(0, currentScroll + (scrollHeight - currentScroll - clientHeight) / 2);
                }
            })();
        }

        {# 聊天websocket #}
        {% if request.user.is_authenticated %}
        const ws_group = Math.max({{ request.user.id }}, {{ recipient_user.id }});
        const ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
        const ws_path = ws_scheme + "://" + window.location.host + "/ws/" + ws_group + "/";
        const ws = new WebSocket(ws_path);
        ws.onmessage = function (event) {
            const data = JSON.parse(event.data);
            if (data['sender'] === '{{ request.user.username }}') {
                var sender_html = '<div class="row">\n' +
                    '        <div class="col">\n' +
                    '            <div class="media">\n' +
                    '                <img src=" ' + data['image'] + ' " class="mr-3" alt="..." style="width: 50px; height: 50px; border-radius: 25px">\n' +
                    '                <div class="media-body">\n' +
                    '                        <div class="chatDialogBoxMe">' + data['message'] + '</div>\n' +
                    '                        <p style="font-size: 10px;color: grey">' + data['time'] + '</p>\n' +
                    '                </div>\n' +
                    '            </div>\n' +
                    '        </div>\n' +
                    '    </div>\n' +
                    '    <br>';
                $("#send_message1").append(sender_html);
                setTimeout(scrollToBottom, 100);
            } else {
                var receive_html = '<div class="row">\n' +
                    '        <div class="col">\n' +
                    '            <div class="media">\n' +
                    '                <img src=" ' + data['image'] + ' " class="mr-3" alt="..." style="width: 50px; height: 50px; border-radius: 25px">\n' +
                    '                <div class="media-body">\n' +
                    '                        <div class="chatDialogBox">' + data['message'] + '</div>\n' +
                    '                        <p style="font-size: 10px;color: grey">' + data['time'] + '</p>\n' +
                    '                </div>\n' +
                    '            </div>\n' +
                    '        </div>\n' +
                    '    </div>\n' +
                    '    <br>';
                $("#send_message1").append(receive_html);
                setTimeout(scrollToBottom, 100);
            }
        };
        {% endif %}

        function sendMessage() {
            $.ajax({
                cache: false,
                type: "POST",
                url: "{% url 'user_message' %}",
                data: {"content": $("#txt").val(), 'user_id': '{{ recipient_user.id }}', 'group': ws_group},
                beforeSend: function (xhr, setting) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                success: function (data) {
                    $("#txt").val('');
                    if (data.status == 'fail'){
                        $("#talk_error").html(data.msg);
                    }else if(data.status == 'success'){
                    }
                }
            })
        }


        {# 删除信息 #}

        function delete_message(message_id) {
            $.ajax({
                cache: false,
                type: "POST",
                url: '{% url 'user_message_delete' %}',
                data: {'message_id': message_id},
                async: true,
                beforeSend: function (xhr, setting) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                success: function (data) {
                    if (data.status == 'fail') {
                        alert(data.msg)
                    } else if (data.status == 'success') {
                        alert(data.msg);
                        window.location.reload()
                    }
                }
            })
        }

    </script>
{% endblock %}
